#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Cookie import BaseCookie
from urllib import quote, unquote


class WsgiCookie(BaseCookie):
    """ A cookie type for WSGI apps.

    This class is a thin wrapper around Cookie.BaseCookie from the
    standard library.  We add a few conviences such as generating a
    list of headers, and automatic url encoding and decoding of cookie
    values.
    """
    def __init__(self, env=None):
        """ Constructs a new WsgiCookie mapping.

        @param env=None WSGI environment or other dictionary
        @return None
        """
        get = (env or {}).get
        BaseCookie.__init__(self, input=get('Cookie', get('HTTP_COOKIE')))

    def wsgi_headers(self, no_cache=True, private=True):
        """ Creates a list of WSGI header two-tuples from this cookie map.

        @param no_cache=True if true, include Cache-control:no-cache header
        @param private=True if true, include Cache-control:private header
        @return list of HTTP response header (name, value) pairs
        """
        hs = [('Set-Cookie', v.OutputString()) for v in self.values()]
        if no_cache:
            hs.append(('Cache-control', 'no-cache="set-cookie"'))
        if private:
            hs.append(('Cache-control', 'private'))
        return hs
 
    def as_dict(self):
        """ Creates a new dictionary with cookie names and simple values.

        @return dict of cookie name and simple value
        """
        return dict((c, self[c].value) for c in self)

    def value_decode(self, val):
        """ Base class hook to decode values.  We apply url unquoting.

        @param val value to decode
        @return unquoted value, value pair
        """
        return unquote(val), val

    def value_encode(self, val):
        """ Base class hook to encode values.  We apply url quoting.
        
        @param val value to encode
        @return value, quoted value pair
        """
        return val, quote(val)
